const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

// 检查模型是否已经存在
const User = mongoose.models.User || (() => {
  const userSchema = new mongoose.Schema({
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      index: true
    },
    email: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      lowercase: true,
      index: true
    },
    phone: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      index: true
    },
    password: {
      type: String,
      required: true,
      select: false
    },
    role: {
      type: String,
      enum: ['admin', 'user', 'guest'],
      default: 'user'
    },
    avatar: {
      type: String,
      default: '/static/default-avatar.png'
    },
    status: {
      type: Boolean,
      default: true
    },
    loginLogs: [{
      ip: String,
      time: Date,
      status: Boolean
    }],
    lastLoginAt: Date,
    lastLogoutAt: Date,
    loginAttempts: {
      type: Number,
      default: 0
    },
    lockUntil: Date,
    refreshToken: {
      type: String,
      select: false
    },
    refreshTokenExpires: {
      type: Date,
      default: () => new Date(Date.now() + 7 * 24 * 3600 * 1000)
    },
    usedRefreshTokens: [{
      token: String,
      expires: Date
    }],
    createdAt: {
      type: Date,
      default: Date.now
    },
    updatedAt: {
      type: Date,
      default: Date.now
    }
  });

  // 密码加密中间件
  userSchema.pre('save', async function(next) {
    if (!this.isModified('password')) return next();
    
    try {
      const salt = await bcrypt.genSalt(10);
      this.password = await bcrypt.hash(this.password, salt);
      next();
    } catch (error) {
      next(error);
    }
  });

  // 验证密码方法
  userSchema.methods.comparePassword = async function(candidatePassword) {
    return bcrypt.compare(candidatePassword, this.password);
  };

  // 更新登录状态
  userSchema.methods.updateLoginStatus = async function(isLogin) {
    if (isLogin) {
      this.status = true;
      this.lastLoginAt = new Date();
      this.loginAttempts = 0;
      this.lockUntil = undefined;
    } else {
      this.status = false;
      this.lastLogoutAt = new Date();
    }
    return this.save();
  };

  // 索引优化
  userSchema.index({ email: 1 });
  userSchema.index({ username: 1 });
  userSchema.index({ phone: 1 });
  userSchema.index({ status: 1 });

  return mongoose.model('User', userSchema);
})();

module.exports = User;